package com.yc.testupload.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.yc.testupload.util.EnvironmentManager;
import com.yc.testupload.util.DatabaseUtil;

// 文档信息类，用于存储重复文档信息
class DuplicateDocumentInfo {
    private int id;
    private String title;
    private String link;

    public DuplicateDocumentInfo(int id, String title, String link) {
        this.id = id;
        this.title = title;
        this.link = link;
    }

    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getLink() {
        return link;
    }
}

@WebServlet(name = "checkDuplicateTitleServlet", value = "/check-duplicate")
public class CheckDuplicateTitleServlet extends HttpServlet {

    // 日志记录器
    private static final Logger logger = LogManager.getLogger(CheckDuplicateTitleServlet.class);
    // 环境管理器
    private EnvironmentManager environmentManager;

    @Override
    public void init() throws ServletException {
        super.init();
        // 初始化环境管理器
        environmentManager = EnvironmentManager.getInstance();
        logger.info("CheckDuplicateTitleServlet初始化完成");
    }

    /**
     * 获取当前环境的二维码域名
     * 
     * @return 二维码域名
     */
    private String getCurrentQrcodeDomain() {
        try {
            Properties config = environmentManager.getCurrentDatabaseConfig();
            String domain = config.getProperty("qrcodeDomain");

            // 如果配置中没有找到，根据当前环境返回默认值
            if (domain == null || domain.trim().isEmpty()) {
                String currentEnv = environmentManager.getCurrentEnvironment();
                domain = EnvironmentManager.ENVIRONMENT_TEST.equals(currentEnv) ? "testdoc2.didaproject.com"
                        : "www.didaidea.com";
                logger.warn("当前环境{}的配置中未找到qrcodeDomain配置，使用默认值: {}", currentEnv, domain);
            } else {
                domain = domain.trim();
                logger.debug("获取到当前环境的二维码域名: {}", domain);
            }

            return domain;
        } catch (Exception e) {
            logger.error("获取二维码域名失败: {}", e.getMessage());
            // 出现异常时返回默认值
            return "testdoc2.didaproject.com";
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();
        String title = request.getParameter("title");

        if (title == null || title.trim().isEmpty()) {
            out.write("{\"code\":0,\"message\":\"标题为空，无需检查重复\"}");
            out.flush();
            return;
        }

        title = title.trim();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DatabaseUtil.getConnection();
            if (conn != null) {
                // 查询数据库中是否存在相同标题的文档，并从wk_file表获取file_url
                String sql = "SELECT w.id, w.title, f.file_url FROM wk_wenku w JOIN wk_file f ON w.file_id = f.file_id WHERE w.title = ?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, title);

                logger.info("执行重复标题检查SQL: {}", sql);
                logger.info("检查的标题: {}", title);

                rs = pstmt.executeQuery();
                List<DuplicateDocumentInfo> duplicates = new ArrayList<>();

                while (rs.next()) {
                    int id = rs.getInt("id");
                    String foundTitle = rs.getString("title");
                    // 动态获取当前环境的二维码域名
                    String currentQrcodeDomain = getCurrentQrcodeDomain();
                    // 使用当前环境的二维码域名格式的链接
                    String fileUrl = "https://" + currentQrcodeDomain + "/wenku/" + id + ".html";
                    duplicates.add(new DuplicateDocumentInfo(id, foundTitle, fileUrl));
                }

                logger.info("发现{}个重复标题的文档", duplicates.size());

                if (duplicates.size() > 0) {
                    // 发现重复标题，返回code=2
                    StringBuilder jsonBuilder = new StringBuilder();
                    jsonBuilder.append("{\"code\":2,\"message\":\"发现重复标题\",\"data\":{\"duplicates\":[");

                    for (int i = 0; i < duplicates.size(); i++) {
                        DuplicateDocumentInfo doc = duplicates.get(i);
                        jsonBuilder.append("{\"id\":")
                                .append(doc.getId())
                                .append(",\"title\":\"").append(escapeJson(doc.getTitle())).append("\",\"link\":\"")
                                .append(escapeJson(doc.getLink())).append("\"}")
                                .append(i < duplicates.size() - 1 ? "," : "");
                    }

                    jsonBuilder.append("]}}");
                    out.write(jsonBuilder.toString());
                } else {
                    // 没有发现重复标题
                    out.write("{\"code\":0,\"message\":\"未发现重复标题\"}");
                }
            } else {
                logger.error("无法获取数据库连接");
                out.write("{\"code\":1,\"message\":\"数据库连接失败\"}");
            }
        } catch (SQLException e) {
            logger.error("检查重复标题时发生数据库错误: {}", e.getMessage());
            out.write("{\"code\":1,\"message\":\"数据库查询失败\"}");
        } finally {
            // 关闭数据库连接
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    logger.error("关闭ResultSet失败", e);
                }
            }
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    logger.error("关闭PreparedStatement失败", e);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    logger.error("关闭Connection失败", e);
                }
            }
        }

        out.flush();
    }

    // 转义JSON字符串中的特殊字符
    private String escapeJson(String input) {
        if (input == null) {
            return "";
        }
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}